package training.osms.controller.category;

import java.util.List;

import org.apache.commons.lang.ObjectUtils;

import training.osms.model.category.Category;
import training.osms.model.category.CategorySearch;
import training.osms.persistence.category.CategoryDAO;

public class CategoryController {

	private CategoryDAO dao;

	public CategoryController(CategoryDAO categoryDAO){
		this.dao = categoryDAO;
	}

	public CategoryController(){
		this.dao = new CategoryDAO();
	}

	public void saveCategory(Category newCategory){
		Category databaseCategory = dao.findCategory(newCategory.getName());

		if (databaseCategory != null){	
			if( ObjectUtils.equals(databaseCategory.getIdentifier(), newCategory.getIdentifier()) == false){
				throw new CategoryAlreadyExistsException();
			}
		}
		if(newCategory.getIdentifier() == null){
			dao.insertCategory(newCategory);
		}else{
			dao.updateCategory(newCategory);
		}


	}

	public List<Category> searchCategory(CategorySearch search) {
		return dao.searchCategories(search);

	}

	public void deleteCategory(Category category) {
		dao.deleteCategory(category);
		
	}

	public int searchCategoryCount(CategorySearch search) {
		return dao.selectCategoryCount(search);
	}
}
